#version 430

in vec3 worldPos;
in vec3 worldNormal;
in vec2 texcoord;
in vec4 FragPosLightSpace;

out vec4 fragColor;

uniform vec3 cameraPos;
uniform vec3 PointLightPos;

layout(binding = 0) uniform sampler2D samp;
layout(binding = 1) uniform sampler2D shadowMap;

float ShadowCalculation(vec4 fragPosLightSpace)
{
    // perform perspective divide
    vec3 projCoords = fragPosLightSpace.xyz / fragPosLightSpace.w;
    // transform to [0,1] range
    projCoords = projCoords * 0.5 + 0.5;
    // get closest depth value from light's perspective (using [0,1] range fragPosLight as coords)
    float closestDepth = texture(shadowMap, projCoords.xy).r; 
    // get depth of current fragment from light's perspective
    float currentDepth = projCoords.z;
    // check whether current frag pos is in shadow
    float shadow = currentDepth > closestDepth+0.0000005  ? 1.0 : 0.0;

    return shadow;
}
void main()
{
	vec3 normal = normalize(worldNormal);
	vec3 viewDir = normalize(cameraPos - worldPos);


	vec3 ambient = vec3(0.2, 0.2, 0.2);

	vec3 lightDirection = normalize(PointLightPos - worldPos);
	vec3 diffuse = max(dot(lightDirection, normal), 0.0) * vec3(1, 1, 1);

	vec3 reflect = normalize(reflect(-lightDirection, normal));
	vec3 specular = pow(max(dot(viewDir, reflect), 0.0), 1000) * vec3(1, 1, 1);
	float shadow = ShadowCalculation(FragPosLightSpace);
	vec4 temp = vec4(ambient + (1-shadow)*(diffuse + specular), 1.0f);
	fragColor = texture(samp, texcoord) * temp;

    // vec3 projCoords = FragPosLightSpace.xyz / FragPosLightSpace.w;
    // // transform to [0,1] range
    // projCoords = projCoords * 0.5 + 0.5;
    // fragColor =vec4(vec3(projCoords.z), 1.0);
}